package com.wy.web;



import com.wy.pojo.User;
import com.wy.service.UserService;
import com.wy.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Base64;

@WebServlet("/user")
public class UserServlet extends BaseServlet {
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //1.获取请求标记
//        String method = request.getParameter("method");
//        //2.判断请求标记,调用指定的方法
//        if("login".equals(method)){
//            login(request,response);
//        }else{
//            response.sendRedirect(request.getContextPath()+"/contact/error.jsp");
//        }
//    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取请求携带的参数信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.封装到User对象中,便于携带数据
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        System.out.println("请求携带的数据为: "+u);
        //3.调用service处理业务逻辑
        UserService service = new UserService();
        User user = service.login(u);
        //4.判断登录的结果
        if(user==null){ // 用户名或密码错误,登录失败
            request.setAttribute("msg","用户名或密码错误");
            //请求转发到登录页面,在登录页面上展示错误的提示信息
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            // 登录成功
            // 保存登录成功的状态: 将登陆成功的用户信息保存到session中,便于下次使用
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //session.setAttribute(session.getId(),user);
            //获取上面的路径
            String oldUrl = (String)session.getAttribute("oldUrl");
            if(oldUrl!=null){
                //重定向到上个页面
                response.sendRedirect(request.getContextPath()+oldUrl);
            }else{
                // 重定向到首页
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }

        }
    }

//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        this.doPost(request, response);
//    }
}